﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis.IData_impl
{
    /// <summary>
    /// 登录日志，接口实现
    /// </summary>
    public sealed class LoginlogDAL_impl : BaseDAL, ILogin_logDAL
    {
        /// <summary>
        /// 添加登录日志
        /// </summary>
        /// <param name="user">登录用户</param>
        /// <param name="stat">1=成功，0=失败</param>
        /// <param name="reamark">描述</param>
        /// 创建时间：2022-11-23 10:37:11。作者：王浩力
        public void AddLoginLog(Login_user user, byte stat, string reamark)
        {
            if (user==null)
            {
                return ;
            }
            Snowflake snowflake = new Snowflake(1, 1);

            //Login_log log = new Login_log();
            //log.Id = snowflake.NextId();
            //log.Login_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //log.Login_user_id = user?.Id ?? 0;
            //log.Account = user?.User_account;
            //log.Real_name = user?.User_real_name;
            //log.Login_stat = stat;
            //log.Remark = reamark;

            string sql = @" INSERT INTO login_log (
                          id,
                          login_user_id,
                          account,
                          real_name,
                          login_time,
                          login_stat,
                          remark
                      )
                      VALUES (
                          $id,
                          $login_user_id,
                          $account,
                          $real_name,
                          $login_time,
                          $login_stat,
                          $remark
                      );";
            Dictionary<string, object> paramesDict = new Dictionary<string, object>();
            paramesDict.Add("$id", snowflake.NextId());
            paramesDict.Add("$login_user_id", user.Id);
            paramesDict.Add("$account", user.User_account);
            paramesDict.Add("$real_name", user.User_real_name);
            paramesDict.Add("$login_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            paramesDict.Add("$login_stat", stat);
            paramesDict.Add("$remark", reamark);

            int count = base.ExecSqlCmd(sql, paramesDict, cmd =>
         {
             return cmd.ExecuteNonQuery();
         });
            if (count > 0)
            {
                LogHelpter.AddLog("新增登录日志成功，用户id=" + user.Id);
            }
        }

        public async Task<PageModel<Login_log>> PageLoginLog(Login_log login_log, int p, int pageRows)
        {
            //   select * from Login_log limit 3 offset 2
            List<Login_log> list = new List<Login_log>();
            System.Data.SQLite.SQLiteConnection connection = null;
            int total = 0;//总记录数
            try
            {
                connection = new System.Data.SQLite.SQLiteConnection(CommonConfig.ConnectionStr);
                await connection.OpenAsync();
                var command = connection.CreateCommand();

                StringBuilder sb = new StringBuilder();
                sb.AppendLine("  select * ");

                //查询总记录数
                sb.AppendLine(" ,(select count(id) from login_log where  login_time>'2022-11-23 08:23:44.332' ) as total  ");
                sb.AppendLine(" from login_log  where  1=1 ");
                if (login_log != null)
                {
                    if (!string.IsNullOrWhiteSpace(login_log.Account))
                    {
                        sb.AppendLine("  and  account=$account  ");
                        command.Parameters.AddWithValue("$account", login_log.Account);
                    }
                    if (!string.IsNullOrWhiteSpace(login_log.Real_name))
                    {
                        sb.AppendLine("  and  real_name like $real_name  ");
                        command.Parameters.AddWithValue("$real_name", "%" + login_log.Real_name + "%");
                    }
                    if (login_log.Login_stat.HasValue)
                    {
                        sb.AppendLine("  and  login_stat=$login_stat  ");
                        command.Parameters.AddWithValue("$login_stat", login_log.Login_stat);
                    }

                    //登录开始时间
                    if (!string.IsNullOrWhiteSpace(login_log.E3))
                    {
                        sb.AppendLine("  and  login_time>=$loginTime_start  ");
                        command.Parameters.AddWithValue("$loginTime_start", login_log.E3);
                    }
                    //登录结束时间
                    if (!string.IsNullOrWhiteSpace(login_log.E4))
                    {
                        sb.AppendLine("  and  login_time>=$loginTime_end  ");
                        command.Parameters.AddWithValue("$loginTime_end", login_log.E4);
                    }

                    if (login_log.Login_user_id > 0)
                    {
                        sb.AppendLine("  and  login_user_id=$login_user_id  ");
                        command.Parameters.AddWithValue("$login_user_id", login_log.Login_user_id);
                    }

                }
                //offset跳过前面多少行
                sb.AppendLine($"  order by  id desc  limit  {pageRows}  offset  {(p - 1) * pageRows} ");
                command.CommandText = sb.ToString();
                var reader = await command.ExecuteReaderAsync();
                while (await reader.ReadAsync())
                {
                    Login_log info = new Login_log();
                    info.Id = reader.GetInt64(0);
                    info.Login_user_id = reader.GetInt64(1);
                    info.Account = reader.GetString(2);
                    info.Login_time = reader.GetString(3);
                    info.Login_stat = reader.GetByte(4);
                    info.Remark = reader.GetString(5);

                    //总记录数
                    if (total == 0)
                    {
                        total = Convert.ToInt32(reader["total"]);
                    }

                    list.Add(info);
                }
            }
            finally
            {
                if (connection != null)
                {
                    await connection.CloseAsync();
                    await connection.DisposeAsync();
                }
            }
            PageModel<Login_log> page = new PageModel<Login_log>();
            page.Total = total;
            page.PageSize = pageRows;
            page.PageIndex = p;
            page.List = list;
            return page;
        }
    }
}
